package com.sl.mes.app.controller.mm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.gson.JsonObject;
import com.sl.mes.app.dao.mm.*;
import com.sl.mes.app.service.mm.MmPickmService;
import com.sl.mes.app.service.puboid.PubOidService;
import com.sl.mes.app.util.HttpUtil;
import com.sl.mes.app.util.JsonHandler;
import com.sl.mes.core.util.JacksonUtil;
import com.sl.mes.core.util.ResponseUtil;
import com.sl.mes.db.dao.BdWkMapper;
import com.sl.mes.db.dao.MmMoMapper;
import com.sl.mes.db.dao.MmPickmMapper;
import com.sl.mes.db.itf.bd.*;
import com.sl.mes.db.itf.mm.IMmMo;
import com.sl.mes.db.itf.mm.IMmPickm;
import com.sl.mes.db.service.mm.MmMoService;
import com.sl.mes.db.vo.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mes/mmpickm")
@Validated
public class MmPickmController {

    @Resource
    private MmPickmService mmPickmService;

    @Resource
    private MmMoService mmMoService;

    @Resource
    private PubOidService pubOidService;

    @Resource
    private IMmPickm iMmPickm;

    @Resource
    private IBdWk iBdWk;

    @Resource
    private IMmMo iMmMo;

    @Resource
    private IBdMaterial iBdMaterial;

    @Resource
    private MmMoMapper mmMoMapper;

    @Resource
    private  BdWkMapper bdWkMapper;

    @Resource
    private IBdDefdoc iBdDefdoc;

    /**
     * 根据id查询备料计划
     * @param
     * @param
     * @return
     */
    @GetMapping("getAggPickmVoById")
    public Object getAggPickmVoById(String cpickmid) {
        AggMmPickmVo aggMmPickmVo = mmPickmService.getAggMmPickmVoById(cpickmid);
        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("aggPickmVo",aggMmPickmVo);
        String s= JSON.toJSONString(aggMmPickmVo);
        System.out.println(s);
        return ResponseUtil.ok(result);
    }

    /**
     * 查询生产订单状态码为1的所有备料计划
     * @return
     */
    @GetMapping("getAllAggPickmVo")
    public Object getAllAggPickmVo() {
        Map<Object,Object> result = new HashMap<>();
        MmPickm mmPickm=null;
        List<MmPickmB> lstMmPickmB=null;
        //查询所有的生产订单进行筛选
        List<MmMo> lstMmMo = iMmMo.selectAllMmMo();
        List<AggMPRecordsVo> lstaggMPRecordsVo = new ArrayList<>();
        for (MmMo mmMo :lstMmMo){
            //未进行备料的生产订单
            if (mmMo.getFbillstatus()==1){
                AggMPRecordsVo aggMPRecordsVo = new AggMPRecordsVo();
                //要料次数
                aggMPRecordsVo.setNumber(mmMo.getVfree1());
                //炉号
                BdWk bdWk  = iBdWk.findById(mmMo.getCwkid());
                String vwkcode = bdWk.getVwkcode();
                aggMPRecordsVo.setBdWk(vwkcode);
                //备料详情
               mmPickm  = iMmPickm.findParentVoByCfirstbillrowid(mmMo.getCmoid());

                //先查询mes系统有没有备料计划如果没有则调用nc服务查询备料计划
                if(mmPickm==null) {
                    //说明mes服务中没有这个生产订单的备料计划调用nc服务进行查询备料计划
                    //连接ncc获取对应的备料计划
                    Map<String, Object> paramsMap = new HashMap<>();
                    String strUrl = "http://192.168.110.80:3006/nccloud/hr/login/HttpSyncDataAction.do";
                    try {
                        Map sysParamMap = new HashMap();
                        sysParamMap.put("cookiets", "1640068633741");
                        sysParamMap.put("pagecs", "1640068633741");
                        sysParamMap.put("appcode", "");
                        net.sf.json.JSONObject sysParamJsonObj = net.sf.json.JSONObject.fromObject(sysParamMap);
                        paramsMap.put("sysParamJson", sysParamJsonObj);
                        String busiParamJson = "{\"busidata\":{\"cpmohid\":\""+mmMo.getCpmohid()+"\",\"cmoid\":\""+mmMo.getCmoid()+"\"},\"busitype\":\"pickm\",\"busioperator\":\"getPickm\",\"key\":\"eyJwa19ncm91cCI6IjAwMDFBNTEwMDAwMDAwMDAwNUZKIiwiZGF0YXNvdXJjZSI6ImMjI25jYzAzMTEiLCJ1c2VyY29kZSI6ImxncSIsInVzZXJpZCI6IjEwMDFBNTEwMDAwMDAwMDAwMVNaIn0=\"}";

                        paramsMap.put("busiParamJson", busiParamJson);
                        String resultNC = HttpUtil.exeApplyJsonObjectRequest(strUrl, paramsMap);

                        JSONObject paramJson = JSONObject.parseObject(resultNC);
                        //如果返回结果不成功
                        String isSuccess = paramJson.getString("success");
                        //如果从mes中没查到,从nc也没有查到说明还没有进行pc的配料直接跳出本次循环进行下一个生产订单的查询
                        if (isSuccess.equals("false")){
                            continue;
                        }

                        JSONArray data=(JSONArray)paramJson.get("data");
                        //备料计划表头
                        JSONObject headJson=(JSONObject)((JSONObject)((JSONObject)data.get(0)).get("parent")).get("valueIndex");

                        //备料计划详情
                        JSONArray resultJsonArray=(JSONArray)((JSONArray)((JSONObject)data.get(0)).get("children")).get(0);

                        //生成要添加的备料计划
                        AggMmPickmVo aggMmPickmVo = new AggMmPickmVo();

                        String headMmpickmStr = headJson.toString();

                        MmPickm insertMmpickm =JsonHandler.fromJson(headMmpickmStr, MmPickm.class);

                        //添加备料计划表头
                        aggMmPickmVo.setMmPickm(insertMmpickm);
                        List<MmPickmB> lstBodyMmPickmB = new ArrayList<>();
                        for (int i = 0; i < resultJsonArray.size(); i++) {
                            String rowStr = ((JSONObject)resultJsonArray.get(i)).get("valueIndex").toString();
                            //从nc查询出来的备料计划
                            MmPickmB bodyMmPickmB =  JsonHandler.fromJson(rowStr, MmPickmB.class);

                            lstBodyMmPickmB.add(bodyMmPickmB);
                        }
                        //添加备料计划表体
                        aggMmPickmVo.setLstMmpickmB(lstBodyMmPickmB);
                        //没有备料计划进行添加操作
                        int intAdded=mmPickmService.addAggMmPcikmVo(aggMmPickmVo);
                        if (intAdded>0){
                            //todo:
                            //添加完再进行数据库的查询
                            mmPickm = iMmPickm.findParentVoByCfirstbillrowid(mmMo.getCmoid());
                            lstMmPickmB = iMmPickm.findChildrenVoById(mmPickm.getCpickmid());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }else{
                    //备料计划详情
                    lstMmPickmB = iMmPickm.findChildrenVoById(mmPickm.getCpickmid());
                }
                //去物料档案进行查询对应的数据
                List<NameNumber> lstNameNumbers = new ArrayList<>();

                for (MmPickmB mmPickmB:lstMmPickmB){
                    NameNumber nameNumber = new NameNumber();
                    //数量
                    String vbdef2 = mmPickmB.getVbdef2();
                    nameNumber.setVbdef2(vbdef2);
                    //总量
                    Double vbdef3 = mmPickmB.getNshouldnum();
                    nameNumber.setVbdef3(vbdef3);

                    //数量
                    Double num =  mmPickmB.getNplanoutastnum();
                    nameNumber.setNumber(num);

                    //物料信息pk值
                    String cpickmbid = mmPickmB.getCpickmBid();
                    nameNumber.setCpickmbid(cpickmbid);

                    BdMaterial  bdMaterial = iBdMaterial.findById(mmPickmB.getCbmaterialid());
                    String name = bdMaterial.getName();
                    //物料名称
                    nameNumber.setName(name);

                    lstNameNumbers.add(nameNumber);
                }
                aggMPRecordsVo.setNameNumbers(lstNameNumbers);
                lstaggMPRecordsVo.add(aggMPRecordsVo);
            }
        }

        result.put("lstaggMPRecordsVo",lstaggMPRecordsVo);
        return ResponseUtil.ok(result);
    }



    /**
     * 根据炉号查询备料计划
     * @param
     * @param
     * @return
     */
    @GetMapping("getAggPickmVoByVrowno")
    public Object getAggPickmVoByVrowno(String vrowno) {
        AggMPRecordsVo aggMPRecordsVo = new AggMPRecordsVo();
        //炉号
        aggMPRecordsVo.setBdWk(vrowno);
        //实际配料量
        aggMPRecordsVo.setHjNumber("0");
        Map<Object, Object> result = new HashMap<Object, Object>();

        //通过炉号在工作中心中查出对应的pk
        BdWk bdWk =iBdWk.findByVwkcode(vrowno);
        String cmoid=bdWk.getVdef2()==null?"":bdWk.getVdef2();//当前订单行pk

        //要料次数
        MmMo mmMo =mmMoMapper.selectByPrimaryKey(cmoid);


        String n =  mmMo.getVfree1();
        aggMPRecordsVo.setNumber(n);

        //流程生产订单
        String cmohid=bdWk.getVdef1()==null?"":bdWk.getVdef1();//当前订单头pk
        if (cmohid.equals("")){
            return ResponseUtil.fail(-2,"未进行配料");
        }
        MmPmo mmPmo = iMmMo.findParentVoById(cmohid);
        aggMPRecordsVo.setVbillcode(mmMo.getVbillcode());

        //状态码
        int fbillstatus = mmMo.getFbillstatus();
        aggMPRecordsVo.setFbillstatus(fbillstatus);

        //申请量
         Double nplanputastnum = mmMo.getNplanputastnum();
         aggMPRecordsVo.setNplanputastnum(nplanputastnum);

        if (!cmoid.equals("")){
            //根据每一个的生产订单的pk查出对应的备料计划
            MmPickm mmPickm= iMmPickm.findParentVoByVsourcemorowid(cmoid);
            if (mmPickm==null){
                return ResponseUtil.fail(-1,"没有对应炉号的备料信息");
            }
            //根据备料表头查表体
            List<MmPickmB> lstMmPickmB = iMmPickm.findMmPickmBByCpickmid(mmPickm.getCpickmid());

            //去物料档案进行查询对应的数据
            List<NameNumber> lstNameNumbers = new ArrayList<>();
            //合计总数量
            Double sumNumber;
            for (MmPickmB mmPickmB :lstMmPickmB){
                NameNumber nameNumber = new NameNumber();

                //生产批次
                String vbdef1 = mmPickmB.getVbdef1();
                nameNumber.setVbdef1(vbdef1);
                //数量
                String vbdef2 = mmPickmB.getVbdef2();
                nameNumber.setVbdef2(vbdef2);
                //总量
                Double vbdef3 = mmPickmB.getNshouldnum();
                nameNumber.setVbdef3(vbdef3);

                //物料信息pk值
                String cpickmbid = mmPickmB.getCpickmBid();
                nameNumber.setCpickmbid(cpickmbid);

                //数量
                Double num =  mmPickmB.getNplanoutastnum();
                nameNumber.setNumber(num);

                BdMaterial  bdMaterial = iBdMaterial.findById(mmPickmB.getCbmaterialid());
                String name = bdMaterial.getName();
                //物料名称
                nameNumber.setName(name);
                lstNameNumbers.add(nameNumber);
            }
            //所有物料
            aggMPRecordsVo.setNameNumbers(lstNameNumbers);

            result.put("aggMPRecordsVo",aggMPRecordsVo);
        }
        return ResponseUtil.ok(result);
    }


    /**
     * 根据炉号查询收料查询
     * @param
     * @param
     * @return
     */
    @GetMapping("getAggPickmVoByRecyclingVrowno")
    public Object getAggPickmVoByRecyclingVrowno(String vrowno) {
        AggMPRecordsVo aggMPRecordsVo = new AggMPRecordsVo();
        //炉号
        aggMPRecordsVo.setBdWk(vrowno);
        //实际配料量
        aggMPRecordsVo.setHjNumber("0");
        Map<Object, Object> result = new HashMap<Object, Object>();

        //通过炉号在工作中心中查出对应的pk
        BdWk bdWk =iBdWk.findByVwkcode(vrowno);
        String cmoid=bdWk.getVdef2()==null?"":bdWk.getVdef2();//当前订单行pk

        //要料次数
        MmMo mmMo =mmMoMapper.selectByPrimaryKey(cmoid);

        //判断是否可以收料
        if (mmMo.getFbillstatus()!=2){
            return ResponseUtil.fail(-9,"不允许进行收料!");
        }

        String n =  mmMo.getVfree1();
        aggMPRecordsVo.setNumber(n);

        //流程生产订单
        String cmohid=bdWk.getVdef1()==null?"":bdWk.getVdef1();//当前订单头pk
        if (cmohid.equals("")){
            return ResponseUtil.fail(-2,"未进行配料");
        }
        MmPmo mmPmo = iMmMo.findParentVoById(cmohid);
        aggMPRecordsVo.setVbillcode(mmMo.getVbillcode());

        //状态码
        int fbillstatus = mmMo.getFbillstatus();
        aggMPRecordsVo.setFbillstatus(fbillstatus);

        //申请量
        Double nplanputastnum = mmMo.getNplanputastnum();
        aggMPRecordsVo.setNplanputastnum(nplanputastnum);

        if (!cmoid.equals("")){
            //根据每一个的生产订单的pk查出对应的备料计划
            MmPickm mmPickm= iMmPickm.findParentVoByVsourcemorowid(cmoid);
            if (mmPickm==null){
                return ResponseUtil.fail(-1,"没有对应炉号的备料信息");
            }
            //根据备料表头查表体
            List<MmPickmB> lstMmPickmB = iMmPickm.findMmPickmBByCpickmid(mmPickm.getCpickmid());

            //去物料档案进行查询对应的数据
            List<NameNumber> lstNameNumbers = new ArrayList<>();
            //合计总数量
            Double sumNumber;
            for (MmPickmB mmPickmB :lstMmPickmB){
                NameNumber nameNumber = new NameNumber();

                //生产批次
                String vbdef1 = mmPickmB.getVbdef1();
                nameNumber.setVbdef1(vbdef1);
                //数量
                String vbdef2 = mmPickmB.getVbdef2();
                nameNumber.setVbdef2(vbdef2);
                //总量
                Double vbdef3 = mmPickmB.getNshouldnum();
                nameNumber.setVbdef3(vbdef3);

                //物料信息pk值
                String cpickmbid = mmPickmB.getCpickmBid();
                nameNumber.setCpickmbid(cpickmbid);

                //数量
                Double num =  mmPickmB.getNplanoutastnum();
                nameNumber.setNumber(num);

                BdMaterial  bdMaterial = iBdMaterial.findById(mmPickmB.getCbmaterialid());
                String name = bdMaterial.getName();
                //物料名称
                nameNumber.setName(name);
                lstNameNumbers.add(nameNumber);
            }
            //所有物料
            aggMPRecordsVo.setNameNumbers(lstNameNumbers);

            result.put("aggMPRecordsVo",aggMPRecordsVo);
        }
        return ResponseUtil.ok(result);
    }



    /**
     * 要料页面查询所有只进行初装的生产订单
     */
    @GetMapping("selectOneMmMo")
    public Object selectOneMmMo(){
        Map<Object,Object> result = new HashMap<>();List<MmMo> lstMmmo  =iMmMo.selectAllMmMo();
        List<AggOneMmMo> lstAggOneMmMo  = new ArrayList<>();
        for (MmMo mmMo :lstMmmo){
            if (mmMo.getFbillstatus() == 1){
                AggOneMmMo aggOneMmMo = new AggOneMmMo();
                //炉号
               String cwkid =  mmMo.getCwkid();
                BdWk bdWk =bdWkMapper.selectByPrimaryKey(cwkid);
                String bdwkname = bdWk.getVwkcode();
                aggOneMmMo.setCwkid(bdwkname);

               //要料次数
                String number = mmMo.getVfree1();
                aggOneMmMo.setNumber(number);

                //产品名称
                String name = mmMo.getCmaterialid();
                BdMaterial bdMaterial = iBdMaterial.findById(name);
                aggOneMmMo.setName(bdMaterial.getName());

                //初装量/复投量
                double  nplanputnum = mmMo.getNplanputnum();
                aggOneMmMo.setNplanputnum(nplanputnum);

                lstAggOneMmMo.add(aggOneMmMo);
            }
        }
        result.put("lstAggOneMmMo",lstAggOneMmMo);
        return ResponseUtil.ok(result);
    }


    /**
     * 要料页面根据炉号查询所有只进行初装的生产订单
     */
    @GetMapping("selectOneMmMoByVrowno")
    public Object selectOneMmMoByVrowno(String vrowno){
        Map<Object,Object> result = new HashMap<>();
        BdWk bdWkByVwkcode = iBdWk.findByVwkcode(vrowno);
        if (bdWkByVwkcode.getVdef2()==null){
            return ResponseUtil.fail(-1,"您输入的炉号没有初投信息!");
        }
        List<MmMo> lstMmmo  =iMmMo.findChildrenVoById(bdWkByVwkcode.getVdef1());
        List<AggOneMmMo> lstAggOneMmMo  = new ArrayList<>();
        for (MmMo mmMo :lstMmmo){
            if (mmMo.getFbillstatus() == 1){
                AggOneMmMo aggOneMmMo = new AggOneMmMo();
                //炉号
                String cwkid =  mmMo.getCwkid();
                BdWk bdWk =bdWkMapper.selectByPrimaryKey(cwkid);
                String bdwkname = bdWk.getVwkcode();
                aggOneMmMo.setCwkid(bdwkname);

                //要料次数
                String number = mmMo.getVfree1();
                aggOneMmMo.setNumber(number);

                //产品名称
                String name = mmMo.getCmaterialid();
                BdMaterial bdMaterial = iBdMaterial.findById(name);
                aggOneMmMo.setName(bdMaterial.getName());

                //初装量/复投量
                double  nplanputnum = mmMo.getNplanputnum();
                aggOneMmMo.setNplanputnum(nplanputnum);

                lstAggOneMmMo.add(aggOneMmMo);
            }else if (mmMo.getFbillstatus()>1){
                return ResponseUtil.fail(-2,"您的初投信息已经备料完了");
            }
        }
        result.put("lstAggOneMmMo",lstAggOneMmMo);
        return ResponseUtil.ok(result);
    }


    /**
     * 根据炉号查询要料记录详情
     */
    @GetMapping("selectOneMmMoByVwkcode")
    public Object selectOneMmMoByVwkcode(String vwkcode){
        Map<Object,Object> result = new HashMap<>();
        BdWk bdWk = iBdWk.findByVwkcode(vwkcode);
        //根据pk查询出对应的生产订单
        MmMo mmMo = mmMoMapper.selectByPrimaryKey(bdWk.getVdef2());
        //实验类型
        BdDefdoc bdDefdoc1 = iBdDefdoc.findById(mmMo.getVdef1());
        String type = bdDefdoc1.getName();
        //坩埚型号
        BdDefdoc bdDefdoc2 = iBdDefdoc.findById( mmMo.getVdef10());
        String model = bdDefdoc2.getName();
        //热长尺寸
        BdDefdoc bdDefdoc3 = iBdDefdoc.findById( mmMo.getVdef11());
        String size = bdDefdoc3.getName();
        //初装/复投量
        double nplanputnum = mmMo.getNplanputnum();
        //产品名称
        BdMaterial bdMaterial = iBdMaterial.findById(mmMo.getCmaterialid());
        String name = bdMaterial.getName();

        result.put("name",name);
        result.put("type",type);
        result.put("model",model);
        result.put("size",size);
        result.put("vwkcode",vwkcode);
        result.put("nplanputnum",nplanputnum);

        return ResponseUtil.ok(result);
    }


    /**
     * 根据id删除备料计划
     * @param
     * @param
     * @return
     */
    @GetMapping("deleteAggPickmVoById")
    public int deleteAggPickmVoById(String cpickmid) {
        return  mmPickmService.deleteAggMmPcikmVoById(cpickmid);
    }


    /**
     * 添加备料计划
     * @param body
     * @param request
     * @return
     */
    @PostMapping("addAggMmPickmVo")
    public Object addAggMmPickmVo(@RequestBody String body, HttpServletRequest request) {

        JsonNode movo = (JsonNode) JacksonUtil.toNode(body);
        //组装AggMoVo
        AggMmPickmVo aggMmPickmVo = new AggMmPickmVo();
        //表头vo
        JsonNode moHead = (JsonNode) ((JsonNode) ((JsonNode) movo.get("data")).get("aggPickmVo")).get("mmPickm");
        MmPickm moHeadVo = JsonHandler.fromJson(moHead.toString(), MmPickm.class);
        String id = pubOidService.generate();
        moHeadVo.setCpickmid(id);

        aggMmPickmVo.setMmPickm(moHeadVo);

        //表体vos
        ArrayNode moBody = (ArrayNode) ((JsonNode) ((JsonNode) movo.get("data")).get("aggPickmVo")).get("lstMmpickmB");
        List<MmPickmB> lstMmPickmB = new ArrayList<>();
        String[] ids = pubOidService.generate(moBody.size());
        for (int i = 0; i < moBody.size(); i++) {
            MmPickmB itemVo = JsonHandler.fromJson(moBody.get(i).toString(), MmPickmB.class);
            itemVo.setCpickmBid(ids[i]);
            itemVo.setCpickmid(id);
            lstMmPickmB.add(itemVo);
        }
        aggMmPickmVo.setLstMmpickmB(lstMmPickmB);

        //调用service的insert方法
        int res = mmPickmService.addAggMmPcikmVo(aggMmPickmVo);
        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("aggMmPickmVo", aggMmPickmVo);
        if (res>0){
            return ResponseUtil.ok(result);
        }else{
            return ResponseUtil.fail();
        }
    }


    /**
     * 修改备料计划
     *
     * @param body
     * @param request
     */
    @PostMapping("updataAggMmPickmById")
    public Object updataAggMmPickmById(@RequestBody String body, HttpServletRequest request) {
        JsonNode movo = (JsonNode) JacksonUtil.toNode(body);
        //修改后单据AggMoVo

        //表头vo
        AggMmPickmVo updatedAggMmPickmVo = new AggMmPickmVo();
        JsonNode moHead = (JsonNode) ((JsonNode) ((JsonNode) movo.get("data")).get("aggPickmVo")).get("mmPickm");
        MmPickm moHeadVo = JsonHandler.fromJson(moHead.toString(), MmPickm.class);
        updatedAggMmPickmVo.setMmPickm(moHeadVo);

        //修改前单据
        String cpickmid = moHeadVo.getCpickmid() == null ? "" : moHeadVo.getCpickmid();
        AggMmPickmVo orignAggMmPickmVo = mmPickmService.getAggMmPickmVoById(cpickmid);
        MmPickm orignMmPickm = orignAggMmPickmVo.getMmPickm();
        List<MmPickmB> orignMoBody = orignAggMmPickmVo.getLstMmpickmB();

        //表体vos
        ArrayNode moBody = (ArrayNode) ((JsonNode) ((JsonNode) movo.get("data")).get("aggPickmVo")).get("lstMmpickmB");
        String[] ids = pubOidService.generate(moBody.size());
        List<MmPickmB> lstNewBody = new ArrayList<MmPickmB>();
        List<MmPickmB> lstUpdateBody = new ArrayList<MmPickmB>();
        List<MmPickmB> lstfinalBody=new ArrayList<MmPickmB>();
        for (int i = 0; i < moBody.size(); i++) {
            MmPickmB itemVo = JsonHandler.fromJson(moBody.get(i).toString(), MmPickmB.class);
            String itemid = itemVo.getCpickmBid() == null ? "" : itemVo.getCpickmBid();
            itemVo.setCpickmid(cpickmid);
            if (itemid.equals("")) {
                String bodyid = pubOidService.generate();
                itemVo.setCpickmBid(bodyid);
                lstNewBody.add(itemVo);
            } else {
                lstUpdateBody.add(itemVo);
                orignMoBody.remove(itemVo);
            }
            lstfinalBody.add(itemVo);
        }
        updatedAggMmPickmVo.setLstMmpickmB(lstfinalBody);

        AggMmPickmVo updateAggMmPickmVo = new AggMmPickmVo();
        AggMmPickmVo newAggMmPickmVo = new AggMmPickmVo();
        AggMmPickmVo delAggMmPickmVo = new AggMmPickmVo();
        if (lstNewBody.size() > 0) {
            newAggMmPickmVo.setMmPickm(moHeadVo);
            newAggMmPickmVo.setLstMmpickmB(lstNewBody);
        } else {
            newAggMmPickmVo = null;
        }
        if (lstUpdateBody.size() > 0) {
            updateAggMmPickmVo.setMmPickm(moHeadVo);
            updateAggMmPickmVo.setLstMmpickmB(lstNewBody);
        } else {
            updateAggMmPickmVo = null;
        }
        if (orignMoBody.size() > 0) {
            delAggMmPickmVo.setMmPickm(orignMmPickm);
            delAggMmPickmVo.setLstMmpickmB(orignMoBody);
        }

        //调用service的insert方法
        boolean res = mmPickmService.updataMmPickm(updateAggMmPickmVo);
        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("updateAggMmPickmVo", updateAggMmPickmVo);
        if (res){
            return ResponseUtil.ok(result);
        }else{
            return ResponseUtil.fail();
        }

    }


    /**
     *  添加备料明细
     *  点击备料完成
     * @param
     * @param
     * @return
     */
    @PostMapping("addMmpickmDetails")
    @Transactional
    public Object addMmpickmDetails(@RequestBody String body, HttpServletRequest request) {
        Map<Object, Object> result = new HashMap<Object, Object>();
        JsonNode movo = (JsonNode) JacksonUtil.toNode(body);
        JsonNode aggMPVo = (JsonNode) ((JsonNode) movo.get("data")).get("aggMPRecordsVo");
        AggMPRecordsVo aggMPRecordsVo = JsonHandler.fromJson(aggMPVo.toString(), AggMPRecordsVo.class);
        //判断是否重复备料
        String vwkcode = aggMPRecordsVo.getBdWk();
        BdWk bdWk = iBdWk.findByVwkcode(vwkcode);
        String cmoid = bdWk.getVdef2();
        MmMo mmMo = mmMoMapper.selectByPrimaryKey(cmoid);
        if(mmMo.getFbillstatus().equals(2) || mmMo.getFbillstatus().equals(3) || mmMo.getFbillstatus().equals(4)){
            return ResponseUtil.fail(-1,"您不可重复备料!");
        }

        List<NameNumber> nameNumbers = aggMPRecordsVo.getNameNumbers();
        //备料表头的数据
         AggMmPickmVo aggMmPickmVo = mmPickmService.getAggMmPickmVoByCfirstbillrowid(mmMo.getCmoid());

        //返回的修改后表体的数据
        List<MmPickmB> lstMmPickmB = new ArrayList<>();
        int res;
        for (NameNumber nameNumber :nameNumbers){
            //想要修改的备料明细pk
            String cpickmbid =nameNumber.getCpickmbid();
            //生产批次号
            String vbdef1 = nameNumber.getVbdef1();
            //生产数量
            String vbdef2 = nameNumber.getVbdef2();
            //总数量
            Double vbdef3 = nameNumber.getVbdef3();
            //根据id获取每一条数据
            MmPickmB  mmPickmB =iMmPickm.findMmPickmBById(cpickmbid);
            mmPickmB.setVbdef1(vbdef1);
            mmPickmB.setVbdef2(vbdef2);
            mmPickmB.setNshouldnum(vbdef3);
            //进行修改
            res = iMmPickm.updateMmPickmB(mmPickmB);
            if (res !=1){
                return ResponseUtil.fail(-1,"修改失败");
            }
            lstMmPickmB.add(mmPickmB);
        }
        aggMmPickmVo.setLstMmpickmB(lstMmPickmB);

        //添加完成修改状态码
        mmMo.setFbillstatus(2);
        mmMoMapper.updateByPrimaryKey(mmMo);

        try {
        //把备料完成的信息返回给ncc
        String url ="http://192.168.110.13:8080/nccloud/hr/login/HttpSyncDataAction.do";
        Map<String,Object> paramsMap = new HashMap<>();
        Map sysParamMap=new HashMap();

        //设置参数中的json对象
        sysParamMap.put("cookiets","1640068633741");
        sysParamMap.put("pagecs", "1640068633741");
        sysParamMap.put("appcode","");

        //转换为json对象
        net.sf.json.JSONObject sysParamJsonObj= net.sf.json.JSONObject.fromObject(sysParamMap);
        paramsMap.put("sysParamJson", sysParamJsonObj);
        //将对象转换成json字符串
        String s= JSON.toJSONString(aggMmPickmVo);
        System.out.println(s);
        String busiParamJson="{\"busidata\": "+s+",\"busitype\":\"pickm\",\"busioperator\":\"updatePickm\",\"key\":\"eyJwa19ncm91cCI6IjAwMDFBNTEwMDAwMDAwMDAwNUZKIiwiZGF0YXNvdXJjZSI6ImMjI25jYzAzMTEiLCJ1c2VyY29kZSI6ImxncSIsInVzZXJpZCI6IjEwMDFBNTEwMDAwMDAwMDAwMVNaIn0=\"}";
        paramsMap.put("busiParamJson", busiParamJson);
            HttpUtil.exeApplyJsonObjectRequest(url,paramsMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //修改的信息进行返回
        result.put("lstMmPickmB",lstMmPickmB);
        return ResponseUtil.ok(result);
    }


    /**
     *点击收料
     */
    @PostMapping("updateMmpickmBStatus")
    @Transactional
    public  Object updateMmpickmBStatus(@RequestBody String body, HttpServletRequest request){
        JsonNode movo = (JsonNode) JacksonUtil.toNode(body);
        JsonNode aggMPVo = (JsonNode) ((JsonNode) movo.get("data")).get("aggMPRecordsVo");
        AggMPRecordsVo aggMPRecordsVo = JsonHandler.fromJson(aggMPVo.toString(), AggMPRecordsVo.class);
        //检查是否重复收料
        String vwkcode = aggMPRecordsVo.getBdWk();
        BdWk bdWk = iBdWk.findByVwkcode(vwkcode);
        String cmoid = bdWk.getVdef2();
        MmMo mmMo = mmMoMapper.selectByPrimaryKey(cmoid);
        if (mmMo.getFbillstatus().equals(3) || mmMo.getFbillstatus().equals(4)){
            return ResponseUtil.fail(-1,"您已经收料过!");
        }else if (mmMo.getFbillstatus().equals(1)){
            return ResponseUtil.fail(-2,"请先进行备料");
        }
        List<NameNumber> nameNumbers = aggMPRecordsVo.getNameNumbers();
        int res=0;

        MmPickmB mmPickmB=null;
        for (NameNumber nameNumber : nameNumbers){
            String cpickmbid  = nameNumber.getCpickmbid();
            Double naccoutnum =  nameNumber.getVbdef3();
            //把收料的数据添加到数据库中
            mmPickmB = iMmPickm.findMmPickmBById(cpickmbid);
            mmPickmB.setNaccoutnum(naccoutnum);
            iMmPickm.updateMmPickmB(mmPickmB);

            MmPickm mmPickm = iMmPickm.findParentVoById(mmPickmB.getCpickmid());
           res = iMmPickm.updateMmPickm(mmPickm);
           if (res!=1){
               return ResponseUtil.fail(-1,"修改失败");
           }
        }
        try {
            //把备料完成的信息返回给ncc
            String url ="http://192.168.110.13:8080/nccloud/hr/login/HttpSyncDataAction.do";
            Map<String,Object> paramsMap = new HashMap<>();
            Map sysParamMap=new HashMap();
            //设置参数中的json对象
            sysParamMap.put("cookiets","1640068633741");
            sysParamMap.put("pagecs", "1640068633741");
            sysParamMap.put("appcode","");

            //转换为json对象
            net.sf.json.JSONObject sysParamJsonObj= net.sf.json.JSONObject.fromObject(sysParamMap);
            paramsMap.put("sysParamJson", sysParamJsonObj);
            //将对象转换成json字符串
            String s= JSON.toJSONString(mmPickmB);
            String busiParamJson="{\"busidata\":"+s+",\"busitype\":\"pickm\",\"busioperator\":\"update\",\"key\":\"eyJwa19ncm91cCI6IjAwMDFBNTEwMDAwMDAwMDAwNUZKIiwiZGF0YXNvdXJjZSI6ImMjI25jYzAzMTEiLCJ1c2VyY29kZSI6ImxncSIsInVzZXJpZCI6IjEwMDFBNTEwMDAwMDAwMDAwMVNaIn0=\"}";
            paramsMap.put("busiParamJson", busiParamJson);
            HttpUtil.exeApplyJsonObjectRequest(url,paramsMap);

        } catch (Exception e) {
            e.printStackTrace();
        }

        //添加完成修改状态码
        mmMo.setFbillstatus(3);
        mmMoMapper.updateByPrimaryKey(mmMo);

        return ResponseUtil.ok(res);
    }


    /**
     * 根据炉号查询报工信息
     * @param
     * @param
     * @return
     */
    @GetMapping("WorkByVrowno")
    public Object WorkByVrowno(String vrowno) {
        Map<Object,Object> result  = new HashMap<>();
        //通过炉号在工作中心中查出对应的pk
        BdWk bdWk =iBdWk.findByVwkcode(vrowno);
        //炉号
        String bdWkVwkcode =bdWk.getVwkcode();
        //发料编码(炉号+当前流程生产订单号)
        String cmoid = bdWk.getVdef2();
        MmMo mmMo = mmMoMapper.selectByPrimaryKey(cmoid);
        //判断炉台信息
        if (mmMo==null){
            return ResponseUtil.fail(-1,"此炉台没有相关信息");
        }
        //返回状态码
        int fbillstatus = mmMo.getFbillstatus();

        String materialCode =bdWkVwkcode+mmMo.getVrowno()+mmMo.getCmoid();
        //物料名称
        String cmaterialid =  mmMo.getCmaterialid();
        BdMaterial bdMaterial = iBdMaterial.findById(cmaterialid);
        String materialName = bdMaterial.getName();

        result.put("bdWkVwkcode",bdWkVwkcode);
        result.put("materialCode",materialCode);
        result.put("materialName",materialName);
        result.put("fbillstatus",fbillstatus);
        return ResponseUtil.ok(result);
    }

}






